package MyUtil;

import java.security.*;
import javax.crypto.*;
import sun.misc.*;

public class MaHoa 
{
    private Key key;
    
    public void TaoKey()
    {
        try
        {
            KeyGenerator kg = KeyGenerator.getInstance("DES");
            kg.init(new SecureRandom());
            key = kg.generateKey();
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
    }
    
    public String MaHoaDuLieu(String content)
    {
        String result = "";        
        try
        {
            // Tao khoa cho viec ma hoa
            this.TaoKey();
            // Tao thuat toan ma hoa            
            Cipher ci = Cipher.getInstance("DES");
            ci.init(Cipher.ENCRYPT_MODE, key);
            // Ma hoa mang byte cua noi dung
            byte []bs = content.getBytes();
            byte []nbs = ci.doFinal(bs);
            // Chuyen mang byte ve thanh chuoi
            BASE64Encoder encode = new BASE64Encoder();
            result = encode.encode(nbs);
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
        return result;
    }    
    
    public String GiaiMa(String content)
    {
        String result = "";        
        try
        {
            Cipher ci = Cipher.getInstance("DES");
            ci.init(Cipher.DECRYPT_MODE, key);
            BASE64Decoder dcode = new BASE64Decoder();
            byte []bs = dcode.decodeBuffer(content);
            byte []nbs = ci.doFinal(bs);
            result = new String(nbs);
        }
        catch(Exception ex)
        {
            System.out.println(ex);
        }
        
        return result;
    }
    
}
